﻿using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Jage.Data;
using Jage.Logic.Resources;

namespace Jage.Logic.Crud
{
    public class Spritesheet
    {

        public static Data.Spritesheet GetNew(string name, int spritesPerRow)
        {
            return new Data.Spritesheet() { Name = name, SpritesheetId = Guid.NewGuid() };
        }

        public static void Delete(Data.Spritesheet spritesheet)
        {
            // check if record is being used:
            if (spritesheet.Sprites.Any(sprite => sprite.AnimationSprites.Count > 0))
            {
                MessageBox.Show("Cannot delete spritesheet: it is not empty because some sprites are being used in an animation.", "Cannot delete", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Delete generated spriteheet file
            if (File.Exists(ResourceIO.GetAbsolute(spritesheet.Resource)))
            {
                File.Delete(ResourceIO.GetAbsolute(spritesheet.Resource));
            }

            // delete children
            foreach (var sprite in JageDb.Default.Sprites.Where(s => s.SpritesheetId == spritesheet.SpritesheetId))
            {
                JageDb.Default.DeleteObject(sprite);
            }
            foreach (var spriteSource in JageDb.Default.SpriteSources.Where(s => s.SpritesheetId == spritesheet.SpritesheetId))
            {
                JageDb.Default.DeleteObject(spriteSource);
            }
            JageDb.Default.DeleteObject(spritesheet);
            JageDb.Default.SaveChanges();
        }

    }
}
